#include "Fan.h"
#include "TinyXML/tinyxml.h"
#include "ChineseEnglishMapping.h"
#include <QDebug>
#include <QVBoxLayout>
#include <QSplitter>

Fan::Fan()
{

}

void Fan::InitUI(const QString &fileName, QList<QPair<QWidget *, QString> > &widgets, QMap<int, QList<TableWidgetForm *> > &m_pTableWidgetFormMap)
{
    QString filePath = QString("%1/config/%2/%3")
            .arg(COMMONS->XmlPath)
            .arg(COMMONS->MachType)
            .arg(fileName);
    FanConnectStr _FanConnectStr;
    QList<QList<Fanstruct> > FanstructList;
    Analysis(filePath,_FanConnectStr,FanstructList);

    //添加第一个表
    QWidget* widget = new QWidget;
    QVBoxLayout *layout = new QVBoxLayout(widget);
    QSplitter *splitter = new QSplitter(Qt::Vertical, widget);
    splitter->setChildrenCollapsible(false);
    layout->addWidget(splitter);
    widgets.append(qMakePair(widget,QStringLiteral("tab0")));

    TableWidgetForm* _TableWidgetForm = new TableWidgetForm(widget);
    splitter->addWidget(_TableWidgetForm);
    _TableWidgetForm->setGroupBoxTitle(QString("%1_0").arg(fileName.left(fileName.size()-4)));

    //获取表头
    _TableWidgetForm->setTableWidgetHeaderLabels(COMMONS->getTableWidgetHeadLabels(fileName,_FanConnectStr.toFieldNames().split(',')));
    _TableWidgetForm->setTableWidgetHeaderType(_FanConnectStr.toFieldTypes());

    _TableWidgetForm->getTableWidget()->setRowCount(1);
    _TableWidgetForm->getTableWidget()->setItem(0, 0, new QTableWidgetItem(_FanConnectStr.name));
    _TableWidgetForm->getTableWidget()->setItem(0, 1, new QTableWidgetItem(_FanConnectStr.type));
    m_pTableWidgetFormMap.insert(0,QList<TableWidgetForm*>() << _TableWidgetForm);

    for (int i = 0;i<FanstructList.size();i+=2)
    {
        QWidget* widget = new QWidget;
        QVBoxLayout *layout = new QVBoxLayout(widget);
        QSplitter *splitter = new QSplitter(Qt::Vertical, widget);
        splitter->setChildrenCollapsible(false);
        layout->addWidget(splitter);
        widgets.append(qMakePair(widget,QStringLiteral("tab%1").arg(i/2+1)));

        for (int j=0;j<2;j++)
        {
            TableWidgetForm* _TableWidgetForm = new TableWidgetForm(widget);
            splitter->addWidget(_TableWidgetForm);
            _TableWidgetForm->setGroupBoxTitle(QString("%1_%2").arg(fileName.left(fileName.size()-4)).arg(i+j));

            //获取表头
            Fanstruct _Fanstructtemp;
            _TableWidgetForm->setTableWidgetHeaderLabels(COMMONS->getTableWidgetHeadLabels(fileName,_Fanstructtemp.toFieldNames().split(',')));
            _TableWidgetForm->setTableWidgetHeaderType(_Fanstructtemp.toFieldTypes());

            for (auto item : FanstructList.at(i+j))
            {
                int rowCount = _TableWidgetForm->getTableWidget()->rowCount();
                _TableWidgetForm->getTableWidget()->setRowCount(rowCount+1);
                _TableWidgetForm->getTableWidget()->setItem(rowCount, 0, new QTableWidgetItem(item.name));
                _TableWidgetForm->getTableWidget()->item(rowCount,0)->setData(Qt::UserRole,item.id);
                _TableWidgetForm->getTableWidget()->setItem(rowCount, 1, new QTableWidgetItem(QString("%1").arg(item.rotate)));
                _TableWidgetForm->getTableWidget()->setItem(rowCount, 2, new QTableWidgetItem(QString("%1").arg(item.maxrotate)));
                _TableWidgetForm->getTableWidget()->setItem(rowCount, 3, new QTableWidgetItem(QString("%1").arg(item.uplimit)));
                _TableWidgetForm->getTableWidget()->setItem(rowCount, 4, new QTableWidgetItem(QString("%1").arg(item.lowlimit)));
                _TableWidgetForm->getTableWidget()->setItem(rowCount, 5, new QTableWidgetItem(QString("%1").arg(item.board_id)));
                _TableWidgetForm->getTableWidget()->setItem(rowCount, 6, new QTableWidgetItem(QString("%1").arg(item.phyid)));
                _TableWidgetForm->getTableWidget()->setItem(rowCount, 7, new QTableWidgetItem(QString("%1").arg(item.enable)));
                _TableWidgetForm->getTableWidget()->setItem(rowCount, 8, new QTableWidgetItem(item.location));
                _TableWidgetForm->getTableWidget()->setItem(rowCount, 9, new QTableWidgetItem(item.phymap));
            }
            QList<TableWidgetForm*> item = m_pTableWidgetFormMap.value(i/2+1);
            m_pTableWidgetFormMap.insert(i/2+1, item << _TableWidgetForm);
        }
    }
}

bool Fan::SaveUI(const QString &fileName, const QMap<int, QList<TableWidgetForm *> > &m_pTableWidgetFormMap)
{
    QString filePath = QString("%1/config/%2/%3")
            .arg(COMMONS->XmlPath)
            .arg(COMMONS->MachType)
            .arg(fileName);
    if(m_pTableWidgetFormMap.size() > 0)
    {
        FanConnectStr _FanConnectStr;
        QList<QList<Fanstruct> > FanstructList;
        if(m_pTableWidgetFormMap.value(0).size() > 0)
        {
            TableWidgetForm* _TableWidgetForm = m_pTableWidgetFormMap.value(0).at(0);
            if(_TableWidgetForm)
            {
                _FanConnectStr.name = _TableWidgetForm->getTableWidget()->item(0,0)->text();
                _FanConnectStr.type = _TableWidgetForm->getTableWidget()->item(0,1)->text();
            }
        }

        QMapIterator<int, QList<TableWidgetForm *> > it(m_pTableWidgetFormMap);
        it.next();
        while (it.hasNext()) {
            it.next();
            for (int i = 0;i<it.value().size();i++)
            {
                QList<Fanstruct> _Fanstructs;
                TableWidgetForm* _TableWidgetForm = it.value().at(i);
                if(_TableWidgetForm)
                {
                    for(int k = 0;k<_TableWidgetForm->getTableWidget()->rowCount();k++)
                    {
                        Fanstruct _Fanstruct;
                        _Fanstruct.id = _TableWidgetForm->getTableWidget()->item(k,0)->data(Qt::UserRole).toInt();
                        _Fanstruct.name = _TableWidgetForm->getTableWidget()->item(k,0)->text();
                        _Fanstruct.rotate = _TableWidgetForm->getTableWidget()->item(k,1)->text().toInt();
                        _Fanstruct.maxrotate = _TableWidgetForm->getTableWidget()->item(k,2)->text().toInt();
                        _Fanstruct.uplimit = _TableWidgetForm->getTableWidget()->item(k,3)->text().toInt();
                        _Fanstruct.lowlimit = _TableWidgetForm->getTableWidget()->item(k,4)->text().toInt();
                        _Fanstruct.board_id = _TableWidgetForm->getTableWidget()->item(k,5)->text().toInt();
                        _Fanstruct.phyid = _TableWidgetForm->getTableWidget()->item(k,6)->text().toInt();
                        _Fanstruct.enable = _TableWidgetForm->getTableWidget()->item(k,7)->text().toInt();
                        _Fanstruct.location = _TableWidgetForm->getTableWidget()->item(k,8)->text();
                        _Fanstruct.phymap = _TableWidgetForm->getTableWidget()->item(k,9)->text();
                        _Fanstructs.append(_Fanstruct);
                    }
                }
                FanstructList.append(_Fanstructs);
            }
        }

        SaveXml(filePath,_FanConnectStr,FanstructList);
        return true;
    }
    return false;
}

void Fan::Analysis(const QString &path, FanConnectStr& _FanConnectStr, QList<QList<Fanstruct> > &FanstructList)
{
    TiXmlDocument* xmlDocument = new TiXmlDocument();
    if(!xmlDocument->LoadFile(path.toStdString().c_str()))
    {
        qDebug() << xmlDocument->ErrorDesc();
        delete xmlDocument;
        return;
    }

    TiXmlElement* rootElement = xmlDocument->FirstChildElement("Fans");
    if(rootElement == nullptr) //节点不存在
    {
        qDebug() << xmlDocument->ErrorDesc();
        delete xmlDocument;
        return;
    }

    if(rootElement)
    {
        TiXmlElement* ConnectStrElement = rootElement->FirstChildElement("ConnectStr");
        if(ConnectStrElement != nullptr)
        {
            _FanConnectStr.name = ConnectStrElement->Attribute("name");
            _FanConnectStr.type = ConnectStrElement->Attribute("type");
        }

        for(TiXmlElement* GroupElement = rootElement->FirstChildElement("Group");
            GroupElement != nullptr; GroupElement = GroupElement->NextSiblingElement("Group"))
        {
            if(GroupElement != nullptr)
            {
                for(TiXmlElement* SubGroupElement = GroupElement->FirstChildElement("SubGroup");
                    SubGroupElement != nullptr; SubGroupElement = SubGroupElement->NextSiblingElement("SubGroup"))
                {
                    QList<Fanstruct> _Fanstructs;
                    if(SubGroupElement != nullptr)
                    {
                        for(TiXmlElement* FanElement = SubGroupElement->FirstChildElement("Fan");
                            FanElement != nullptr; FanElement = FanElement->NextSiblingElement("Fan"))
                        {
                            if(FanElement)
                            {
                                Fanstruct _Fanstruct;
                                FanElement->QueryIntAttribute("id", &_Fanstruct.id);
                                _Fanstruct.name = FanElement->Attribute("name");
                                FanElement->QueryIntAttribute("rotate", &_Fanstruct.rotate);
                                FanElement->QueryIntAttribute("maxrotate", &_Fanstruct.maxrotate);
                                FanElement->QueryIntAttribute("uplimit", &_Fanstruct.uplimit);
                                FanElement->QueryIntAttribute("lowlimit", &_Fanstruct.lowlimit);
                                FanElement->QueryIntAttribute("board_id", &_Fanstruct.board_id);
                                FanElement->QueryIntAttribute("phyid", &_Fanstruct.phyid);
                                FanElement->QueryIntAttribute("enable", &_Fanstruct.enable);
                                _Fanstruct.location = FanElement->Attribute("location");
                                _Fanstruct.phymap = FanElement->Attribute("phymap");
                                _Fanstructs.append(_Fanstruct);
                            }
                        }
                    }
                    FanstructList.append(_Fanstructs);
                }
            }
        }
    }
    delete xmlDocument;
}

bool Fan::SaveXml(const QString &path, const FanConnectStr &_FanConnectStr, const QList<QList<Fanstruct> > &FanstructList)
{
    TiXmlDocument* xmlDocument = new TiXmlDocument();
    if(!xmlDocument->LoadFile(path.toStdString().c_str()))
    {
        qDebug() << xmlDocument->ErrorDesc();
        delete xmlDocument;
        return false;
    }

    TiXmlElement* rootElement = xmlDocument->FirstChildElement("Fans");
    if(rootElement == nullptr) //节点不存在
    {
        qDebug() << xmlDocument->ErrorDesc();
        delete xmlDocument;
        return false;
    }

    if(rootElement)
    {
        TiXmlElement* ConnectStrElement = rootElement->FirstChildElement("ConnectStr");
        if(ConnectStrElement != nullptr)
        {
            ConnectStrElement->SetAttribute("name",_FanConnectStr.name.toStdString().c_str());
            ConnectStrElement->SetAttribute("type",_FanConnectStr.type.toStdString().c_str());
        }

        int index = 0;
        for(TiXmlElement* GroupElement = rootElement->FirstChildElement("Group");
            GroupElement != nullptr; GroupElement = GroupElement->NextSiblingElement("Group"))
        {
            if(GroupElement != nullptr)
            {
                for(TiXmlElement* SubGroupElement = GroupElement->FirstChildElement("SubGroup");
                    SubGroupElement != nullptr; SubGroupElement = SubGroupElement->NextSiblingElement("SubGroup"))
                {
                    QList<Fanstruct> _Fanstructs;
                    if(SubGroupElement != nullptr)
                    {
                        for(TiXmlElement* FanElement = SubGroupElement->FirstChildElement("Fan");
                            FanElement != nullptr; FanElement = FanElement->NextSiblingElement("Fan"))
                        {
                            if(FanElement)
                            {
                                SubGroupElement->RemoveChild(FanElement);
                            }
                        }

                        for (auto _Fanstruct : FanstructList.at(index))
                        {
                            //元素类
                            TiXmlElement* ChildxmlElement = new TiXmlElement("Fan");
                            ChildxmlElement->SetAttribute("id", _Fanstruct.id);
                            ChildxmlElement->SetAttribute("name", _Fanstruct.name.toStdString().c_str());
                            ChildxmlElement->SetAttribute("rotate", _Fanstruct.rotate);
                            ChildxmlElement->SetAttribute("maxrotate", _Fanstruct.maxrotate);
                            ChildxmlElement->SetAttribute("uplimit", _Fanstruct.uplimit);
                            ChildxmlElement->SetAttribute("lowlimit", _Fanstruct.lowlimit);
                            ChildxmlElement->SetAttribute("board_id", _Fanstruct.board_id);
                            ChildxmlElement->SetAttribute("phyid", _Fanstruct.phyid);
                            ChildxmlElement->SetAttribute("enable", _Fanstruct.enable);
                            ChildxmlElement->SetAttribute("location", _Fanstruct.location.toStdString().c_str());
                            ChildxmlElement->SetAttribute("phymap", _Fanstruct.phymap.toStdString().c_str());
                            SubGroupElement->LinkEndChild(ChildxmlElement);
                        }
                        index++;
                    }
                }
            }
        }
    }

    //保存
    xmlDocument->SaveFile(path.toStdString().c_str());

    delete xmlDocument;
    return true;
}
